<template>
  <div class="center_page">
    <top-bar/>
    <div style="color: blue;display: flex;justify-content: end;margin: 10px;text-decoration-line: underline;cursor: pointer" @click="outLogin">退出登录</div>
    <div class="user_top">
      <div class="user_avator" id="avatorEle">
        <img :src="userHead">
        <div class="change_avator" id="changeEle" @click="changeUserHead">
          <img src="@/assets/userCenter/changeHeader.png">
        </div>
      </div>
      <div class="basic_info">
        <div class="basic_col">
          <div class="info_item"><span class="item_type">账号ID：</span> <span class="item_value">{{
              userId ? userId : '暂无'
            }}</span>
          </div>
          <div class="info_item"><span class="item_type">用户名：</span> <span
            class="item_value">{{ nickName ? nickName : '暂无' }}</span>
            <span class="update_info" @click="updateUserInfo('1')">修改</span>
          </div>
          <div class="info_item"><span class="item_type">手机号：</span> <span
            class="item_value">{{ phonenumber ? phonenumber : '暂无' }}</span>
            <span class="update_info" @click="updateUserInfo('2')">修改</span>
          </div>
        </div>
        <div class="basic_col">
          <div class="info_item"><span class="item_type">性别：</span> <span class="item_value">{{
              sex == 0 ? '男' : sex == 1 ? '女' : '未知'
            }}</span><span
            class="update_info" @click="updateUserInfo('3')">修改</span>
          </div>
          <div class="info_item"><span class="item_type">邮箱：</span> <span
            class="item_value">{{ email ? email : '未知' }}</span>
            <span class="update_info" @click="updateUserInfo('4')">修改</span>
          </div>
          <div class="info_item"><span class="item_type">余额：</span> <span
            class="item_value">{{ money ? money : '0' }}</span>
            <span class="update_info" @click="updateUserInfo('5')">充值</span>
          </div>
        </div>
      </div>
      <el-dialog :title="updateTitle" :visible.sync="dialogTableVisible" @close="submitUpdate" :show-close="false">
        <el-input v-model="updateInfo" v-show="!isUpdateSex&&!isUpdateMoney"></el-input>
        <el-input v-model="updateMoney" v-show="isUpdateMoney" type="number"></el-input>
        <el-select v-model="updateSex" placeholder="请选择性别" v-show="isUpdateSex">
          <el-option label="男" value="0"></el-option>
          <el-option label="女" value="1"></el-option>
        </el-select>
      </el-dialog>
      <input type="file" id="file-input" style="opacity: 0">
    </div>
    <div class="park_record">
      <div class="record_title">停车记录</div>
      <div v-for="(item,index) in parkRecordList" :key="index" style="border-bottom: 1px #ddd dashed; padding: 20px; display: flex; align-items: center;margin: 20px;padding-left: 200px" v-if="parkRecordList.length>0">
        <div>
          <div class="record_item"><span class="item_type">车位编号：</span><span class="item_value">{{item.spotCode}}</span></div>
          <div class="record_item"><span class="item_type">入库时间：</span><span class="item_value">{{item.warehousingTime.substring(0,19).replace(/T/g, " ")}}</span></div>
          <div class="record_item" v-if="item.amountConsumption"><span class="item_type">消费金额：</span><span class="item_value">{{item.amountConsumption}}</span></div>
          <div class="record_item" v-if="item.qutboundTime"><span class="item_type">出库时间：</span><span class="item_value">{{item.qutboundTime}}</span></div>
        </div>
        <div class="to_out" v-if="!item.qutboundTime" @click="toOutPark">去出库></div>
      </div>
      <div style="display: flex;justify-content: center;margin: 20px">暂无停车记录，点击<span style="color: blue;text-decoration-line: underline;cursor:pointer;" @click="goToPark">去停车</span></div>
    </div>
    <div style="height: 70vh"></div>
  </div>
</template>
<script>
import topBar from "../components/topBar.vue";

export default {
  components: {
    topBar

  },
  data() {
    return {
      uploadHeaders: {
        Authorization: 'Bearer ' + window.localStorage.getItem('access_token'),
      },
      userHead: '',
      nickName: '',
      userName: '',
      userId: '',
      phonenumber: '',
      sex: '',
      email: '',
      updateInfo: '',
      updateTitle: '',
      updateSex: '',
      dialogTableVisible: false,
      isUpdateSex: false,
      updateType: '',
      action: window.API_BASE_URL + 'system/user/profile/avatar',
      personEditimage: '',
      imageUrl: '',
      money: '',
      updateMoney: '',
      isUpdateMoney: false,
      parkRecordList: []
    }
  },
  methods: {
    outLogin(){
      let that = this
      this.$confirm('是否确定退出登录', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(() => {
        that.$axios.get('/logout' , null).then((res) => {
          if (res.data.code == 200) {
            console.log(res)
            localStorage.removeItem('access_token');
            that.$message({
              type: 'success',
              message: '退出登录成功'
            });
            that.$router.push('/')
          } else {
            this.$notify.error({
              title: '错误',
              message: '退出登录失败！'
            });
          }
        }).catch((error) => {
          this.$notify.error({
            title: '错误',
            message: '退出登录失败！'
          });
        });
      }).catch(() => {
      });

    },
    changeUserHead() {
      const fileInput = document.getElementById('file-input');
      fileInput.click()
    },
    uploadDeadImg() {
      let that = this
      const fileInput = document.getElementById('file-input');
      fileInput.addEventListener('change', (event) => {
        const selectedFile = event.target.files[0];
        let param = {
          avatarfile: selectedFile
        }
        console.log(param)
        that.$axios.post('system/user/profile/avatar', param, {
          headers: {
            'Content-Type': 'multipart/form-data;'
          }
        }).then((data) => {
          if (data.data.code == 200) {
            that.getUserInfo()
            this.$message.error('上传成功');
          } else {
            this.$message.error('上传失败，请重试！');
          }
        }).catch((error) => {
          this.$message.error('上传失败，请重试！');
        });
      });
    },
    goToPark(){
      this.$router.push({
        path: '/enterPark'
      })
    },
    updateUserInfo(type) {
      this.updateInfo = ''
      this.updateMoney = ''
      this.updateSex= ''
      this.updateType = type
      this.dialogTableVisible = true
      if (type == '1') {
        this.isUpdateMoney = false
        this.isUpdateSex = false
        this.updateTitle = '修改用户名'
      }
      if (type == '2') {
        this.isUpdateMoney = false
        this.isUpdateSex = false
        this.updateTitle = '修改手机号'
      }
      if (type == '3') {
        this.isUpdateMoney = false
        this.updateTitle = '修改性别'
        this.isUpdateSex = true
      }
      if (type == '4') {
        this.isUpdateMoney = false
        this.isUpdateSex = false
        this.updateTitle = '修改邮箱'
      }
      if(type == '5'){
        this.isUpdateMoney = true
        this.isUpdateSex = false
        this.updateTitle = '请填写充值金额'
      }

    },
    validEmail(email) {
      let emailRegExp = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      return emailRegExp.test(email)
    },
    validPhone(phoneNumber) {
      let phoneRegExp = /^1[3-9]\d{9}$/;
      return phoneRegExp.test(phoneNumber)
    },
    submitUpdate() {

      if (this.updateInfo == ''&&this.updateMoney&&this.updateSex) {
        return
      }
      let that = this
      let param = {
        nickName: this.nickName,
        email: this.email,
        phonenumber: this.phonenumber,
        sex: this.sex,
        money: 0
      }
      if (this.updateType == '1') {
        param.nickName = this.updateInfo
      } else if (this.updateType == '2') {
        if (this.validPhone(this.updateInfo)) {
          param.phonenumber = this.updateInfo
        } else {
          that.$notify.error({
            title: '错误',
            message: '请输入正确格式的手机号码！'
          });
          return
        }
      } else if (this.updateType == '3') {
        param.sex = this.updateSex
      } else if (this.updateType == '4') {
        if (this.validEmail(this.updateInfo)) {
          param.email = this.updateInfo
        } else {
          that.$notify.error({
            title: '错误',
            message: '请输入正确格式的电子邮箱！'
          });
          return
        }

      }else if(this.updateType == '5'){
        param.money = this.updateMoney
      }
      this.$axios.put('system/user/profile', param).then((res) => {
        if (res.data.code == 200) {
          that.getUserInfo()
          that.$notify({
            title: '成功',
            message: '用户信息修改成功！',
            type: 'success'
          });
        }
      }).catch((error) => {
        that.$notify.error({
          title: '错误',
          message: '用户信息修改失败！'
        });
      });
    },
    getUserInfo() {
      let that = this
      this.$axios.get('system/user/profile', null).then((res) => {
        if (res.data.code == 200) {
          that.userId = res.data.data.userName;
          that.nickName = res.data.data.nickName;
          that.phonenumber = res.data.data.phonenumber
          that.sex = res.data.data.sex
          that.email = res.data.data.email
          that.money =res.data.data.money?res.data.data.money:'0'
          // that.getList();
          if (res.data.data.avatar) {

            that.userHead =window.API_BASE_URL + res.data.data.avatar.substring(1)
          } else {
            that.userHead = require('@/assets/userCenter/defaultHead.jpg')
          }
          that.$forceUpdate()
        } else {
          this.$notify.error({
            title: '错误',
            message: '获取用户信息失败！'
          });
        }
      }).catch((error) => {
        this.$notify.error({
          title: '错误',
          message: '获取用户信息失败！'
        });
      });
    },
    getParkInfo(){
      let that = this
      this.$axios.get('system/userSpotInfo/getUserSpotList', null).then((res) => {
        if (res.data.code == 200) {
          console.log(res)
          that.parkRecordList = res.data.rows
        } else {
          this.$notify.error({
            title: '错误',
            message: '获取停车信息失败！'
          });
        }
      }).catch((error) => {
        this.$notify.error({
          title: '错误',
          message: '获取停车信息失败！'
        });
      });
    },
    toOutPark(){
      this.$router.push({
        path: '/outPark'
      })
    }
  },
  created() {
    this.getUserInfo()
    this.getParkInfo()
  },
  mounted() {
    let avatorEle = document.getElementById('avatorEle')
    let changeEle = document.getElementById('changeEle')
    avatorEle.addEventListener('mouseover', () => {
      changeEle.style.display = 'block'
    })
    avatorEle.addEventListener('mouseout', () => {
      changeEle.style.display = 'none'
    })
    this.uploadDeadImg()
  },
}
</script>

<style scoped>

.center_page {
  background-color: #f7f8fa;
}

.user_avator img {
  width: 150px;
  height: 150px;
  border-radius: 50%;
}

.user_avator {
  position: relative;
  margin: 40px;
}

.change_avator {
  position: absolute;
  background-color: rgba(255, 255, 255, .7);
  width: 150px;
  bottom: 0px;
  height: 50px;
  cursor: pointer;
  display: none;
}

.change_avator img {
  margin-left: 65px;
  margin-top: 10px;
  width: 25px;
  height: 25px;
}

.user_top {
  margin: 50px auto;
  width: 2300px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #fff;
  border-radius: 10px;
}

.basic_info {
  display: flex;
  margin-left: 50px;
}

.basic_col {
  width: 500px;
  font-size: 16px;
}

.item_type {
  color: #4E5969;
  font-weight: bold;
}

.item_value {
  margin-left: 50px;
}

.info_item {
  margin-bottom: 10px;
}

.update_info {
  margin-left: 20px;
  color: #165DFF;
  cursor: pointer;
}

.el-select {
  width: 100%;
}

.park_record{
  margin: 50px auto;
  width: 2300px;
  background-color: #fff;
  border-radius: 10px;
  padding-bottom: 20px;
}

.record_title{
  padding: 20px;
  font-size: 20px;
  font-weight: bold;
}

.to_out{
  margin-left: 900px;
  color: #80a2ef;
  cursor: pointer;
}

record_item{
  margin-bottom: 10px;
}
</style>
